import { ref, computed } from 'vue'
import { useVideoStore } from '../renderer/stores/videoStore'
import { VideoService } from '../services/videoService'
import { handleError, createErrorMessage } from '../utils/error'
import { PLAYER } from '../constants/player'
import { rafThrottle } from '../utils/performance'

export function useVideoPlayer() {
  const videoStore = useVideoStore()
  const videoRef = ref(null)
  const duration = ref(0)

  const progress = computed(() => {
    if (!duration.value) return 0
    return (videoStore.currentTime / duration.value) * 100
  })

  const onTimeUpdate = rafThrottle(() => {
    if (!videoRef.value) return
    videoStore.currentTime = videoRef.value.currentTime
  })

  const onVideoLoaded = async () => {
    if (!videoRef.value) return
    duration.value = videoRef.value.duration
    
    if (videoStore.currentVideo) {
      try {
        await VideoService.updateDuration(
          videoStore.currentVideo.originalPath,
          duration.value
        )
      } catch (error) {
        console.error(createErrorMessage('更新视频时长', error))
      }
    }

    videoRef.value.play().catch(error => {
      console.error(createErrorMessage('自动播放', error))
    })
  }

  const jumpToTime = (time) => {
    if (!videoRef.value) return
    videoRef.value.currentTime = Math.max(0, Math.min(time, duration.value))
  }

  return {
    videoRef,
    duration,
    progress,
    onTimeUpdate,
    onVideoLoaded,
    jumpToTime
  }
} 